package com.metacube.questionbank.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.metacube.questionbank.dao.UserDAO;
import com.metacube.questionbank.dto.UserDTO;
import com.metacube.questionbank.service.Utility;
import com.metacube.questionbank.service.Validator;

@Controller
@RequestMapping("/profile")
public class ProfileController {
	
	@Autowired
	Validator validate;
	
	@Autowired
	Utility utility;
	
	@Autowired
	UserDAO userDAO;
	
	@RequestMapping(value = "/editProfile", method = RequestMethod.GET)
	public String profileManage(@ModelAttribute UserDTO userDTO) {
		
		System.out.println("name : "+userDTO.getName());
		userDTO.setId(11);
		
		userDAO.updateProfile(userDTO);
		
		return "welcome";
	}
	
	@RequestMapping(value = "/changePassword", method = RequestMethod.POST)
	public ModelAndView passwordManage(@RequestParam("currentPassword") String currentPassword, @RequestParam("password") String password) {
		
		if(validate.checkChangePassword(password, currentPassword)) {
			
			return new ModelAndView("change_password.jsp","errorMessage","Password fields are Empty");
		}
		
		if(currentPassword.equals(password)) {
			
			return new ModelAndView("change_password.jsp","errorMessage","Both password are same");
		}
	
		if(validate.changePassword(password, currentPassword)) {
			
			return new ModelAndView("change_password.jsp","successMessage","Your password successfully Updated");
			
		} else {
			
			return new ModelAndView("change_password.jsp","errorMessage","your password is wrong");
		}
			
	}
	
	@RequestMapping(value = "/changePhoto", method = RequestMethod.GET)
	public String photoManage(@ModelAttribute UserDTO userDTO) {
		
		userDTO.setId(0);
		
		userDAO.updateProfile(userDTO);
		
		return "profile.jsp";
	}
	
	 @RequestMapping(value = "/getProfile")
	    public ModelAndView getUserProfile(HttpServletRequest req) {

	        String id = req.getParameter("userId");
	        int userId = Integer.parseInt(id);
	        ModelAndView model = new ModelAndView("profile.jsp");
	        List<UserDTO> userProfile = utility.retrieveProfile(userId);
	        model.addObject("userProfile",userProfile);
	        return model;
	    }

}
